package controller;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;

@WebServlet("/hi")
public class SayHi extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取 Cookie 信息，访问上一次访问浏览器的时间
        Cookie[] cookies = req.getCookies();
        StringBuilder afterTime = new StringBuilder();
        String ymd = null; //年月日
        String hms = null; //时分秒
        for(Cookie cookie : cookies) {
            if (cookie.getName().equals("afterTimeYMD")) {
                ymd = cookie.getValue();
            }
            if(cookie.getName().equals("afterTimeHMS")) {
                hms = cookie.getValue();
            }
        }
        //2.创建 Cookie 信息，记录当前访问浏览器的时间
        //非空校验
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //当前时间的年月日
        Cookie curTimeYMD = new Cookie("afterTimeYMD", simpleDateFormat.format(System.currentTimeMillis()).split(" ")[0]);
        //当前时间的时分秒
        Cookie curTimeHMS = new Cookie("afterTimeHMS", simpleDateFormat.format(System.currentTimeMillis()).split(" ")[1]);
        if(ymd == null || hms == null) {
            //添加当前访问浏览器的时间
            resp.addCookie(curTimeYMD);
            resp.addCookie(curTimeHMS);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("您第一次访问该网站!");
            return;
        }
        resp.addCookie(curTimeYMD);
        resp.addCookie(curTimeHMS);
        //3.将上一次访问浏览器的时间返回给浏览器
        resp.setContentType("text/html; charset=utf8");
        //处理时间格式为 yyyy年MM月dd天 HH时mm分ss秒
        handlerTime(afterTime, ymd, hms);
        resp.getWriter().write("您上次访问本程序的时间是：" + afterTime);
    }

    /**
     * 处理时间格式
     * @param afterTime
     * @param ymd
     * @param hms
     */
    private void handlerTime(StringBuilder afterTime, String ymd, String hms) {
        String[] ymds = ymd.split("-");
        afterTime.append(ymds[0]);
        afterTime.append("年");
        afterTime.append(ymds[1]);
        afterTime.append("月");
        afterTime.append(ymds[2]);
        afterTime.append("日");
        afterTime.append(" ");
        String[] hmss = hms.split(":");
        afterTime.append(hmss[0]);
        afterTime.append("时");
        afterTime.append(hmss[1]);
        afterTime.append("分");
        afterTime.append(hmss[2]);
        afterTime.append("秒");
    }


}
